import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import { getStorage } from "../utils/auth";

import pinia from "@/store/store";
import { useRouterStore } from "@/store/index";
const store = useRouterStore(pinia);
import NProgress from "nprogress";
const routerStore = useRouterStore();

// 定义登录路由
const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index.vue"),
  },
];
const router = createRouter({
  history: createWebHistory(),
  routes,
});

//路由前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start();
  // 判断是否有token 否则去登录页 ，暂时不需要token
  if (!getStorage("token") && to.path === "./login") {
    return next({ path: "./login" });
  }
  // 判断是否已经添加路由，否则组装路由文件
  if (!routerStore.permissionList.length) {
    routerStore.fetchPermission().then(() => {
      next(to.path);
    });
  } else {
    next();
  }
});

//路由后置守卫
router.afterEach((to, from, next) => {
  NProgress.done();
  try {
    if (to.meta.name) {
      document.title = to.meta.name;
    }
  } catch (error) {
    console.log(error);
  }
  const routerList = to.matched;
  // 设置面包屑
});
export default router;
